package com.wans.guli.member.service.impl;

import com.wans.guli.common.utils.R;
import com.wans.guli.member.feign.IntegrationFeignClient;
import com.wans.guli.member.vo.OAuthUserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wans.guli.common.utils.PageUtils;
import com.wans.guli.common.utils.Query;

import com.wans.guli.member.dao.MemberDao;
import com.wans.guli.member.entity.MemberEntity;
import com.wans.guli.member.service.MemberService;


@Service("memberService")
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private IntegrationFeignClient integrationFeignClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberEntity member) {
        // 校验 手机号、用户名是否被注册过
        Long mobile = this.lambdaQuery().eq(MemberEntity::getMobile, member.getMobile()).count();
        Long username = this.lambdaQuery().eq(MemberEntity::getUsername, member.getUsername()).count();
        if (mobile > 0)
            throw new RuntimeException("手机号已被注册");
        if (username > 0)
            throw new RuntimeException("用户名已被注册");

        // 密码进行MD5加密
        member.setPassword(BCrypt.hashpw(member.getPassword(), BCrypt.gensalt()));

        // 设置注册时间
        member.setCreateTime(new Date());
        // 设置默认等级
        member.setLevelId(1L);
        // 插入
        this.save(member);

    }

    @Override
    public R getUserInfo(String accessToken) {
        // 获取用户信息 - gitee
        R userInfoR = integrationFeignClient.getUserInfo(accessToken);
        if (userInfoR.getCode() != 0) {
            log.error("远程获取用户社交信息失败");
            log.error((String) userInfoR.get("msg"));
            return R.error("远程获取用户社交信息失败");
        }
        // 获取用户信息成功
        OAuthUserInfoVO userInfo = userInfoR.getData(OAuthUserInfoVO.class);
        // 获取用户唯一ID
        String id = userInfo.getId();
        // 获取用户名
        String name = userInfo.getName();
        // 获取头像
        String avatar_url = userInfo.getAvatar_url();

        // 查看用户信息是否存在 - 根据 userInfo.getId()
        MemberEntity member = this.lambdaQuery().eq(MemberEntity::getGiteeId, Long.parseLong(id)).one();
        if (member != null) {
            // 用户存在 - 注册过
            return R.success(member);
        }

        // 用户不存在 - 新用户
        member = new MemberEntity();
        member.setGiteeId(Long.parseLong(id));
        member.setUsername(name);
        member.setNickname(name);
        member.setHeader(avatar_url);
        member.setCreateTime(new Date());
        member.setLevelId(1L);
        boolean save = this.save(member);
        if (save)
            return R.success(member);

        log.error("用户注册失败");
        return R.error("注册失败");
    }

    /**
     * 登录
     *
     * @param loginAccount 登录账号、手机号、邮箱
     * @param password     密码
     */
    @Override
    public MemberEntity login(String loginAccount, String password) {
        // 查询用户信息
        MemberEntity member = this.lambdaQuery()
                .eq(MemberEntity::getMobile, loginAccount) // 手机号
                .or()
                .eq(MemberEntity::getUsername, loginAccount)  // 用户名
                .one();
        // 判断用户是否存在
        if (member == null)
            throw new RuntimeException("用户不存在");
        // 验证密码
        if (!BCrypt.checkpw(password, member.getPassword()))
            throw new RuntimeException("密码错误");
        // 登录成功
        log.info("用户登录成功");
        // 消除敏感信息
        member.setGiteeId(null);
        member.setLevelId(null);
        member.setStatus(null);
        member.setCreateTime(null);
        member.setGrowth(null);
        member.setIntegration(null);

        return member;
    }

}